from fastapi import APIRouter, File, UploadFile, Form, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
import uuid
from docx import Document
import io
import logging
from app.core.chains import get_resume_evaluation_chain
from app.core.memory.memory_manager import get_session_history
# from app.core import factories, db_connect


# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter()


class Resume_Evaluate_Request(BaseModel):
    position_id: int = Field(..., description="ID of the position the user is applying for.")
    conversation_id: Optional[str] = Field(None,
                                           description="A unique ID for the conversation. If not provided, a new one will be generated.")


class Resume_Evaluate_Response(BaseModel):
    answer: str
    conversation_id: str
    success: bool = False


def docx_to_text(file_content: bytes) -> str:
    """将Word文档内容转换为纯文本"""
    try:
        # 使用内存中的字节流处理文件
        doc_stream = io.BytesIO(file_content)
        doc = Document(doc_stream)

        full_text = []
        for para in doc.paragraphs:
            full_text.append(para.text)

        return '\n'.join(full_text)
    except Exception as e:
        logger.error(f"Word文件处理失败: {str(e)}")
        raise HTTPException(
            status_code=400,
            detail=f"无法处理Word文件: {str(e)}"
        )


@router.post("/", response_model=Resume_Evaluate_Response)
async def evaluate_resume(
        conversation_id: Optional[str] = Form(None),
        resume: UploadFile = File(...)
):
    """
    处理简历评估请求，接收Word文件并将其转换为文本
    """
    try:
        # 验证文件类型
        if resume.filename and not resume.filename.lower().endswith(('.docx', '.doc')):
            raise HTTPException(
                status_code=400,
                detail="只支持.docx或.doc格式的Word文档"
            )

        # 读取文件内容
        file_content = await resume.read()

        # 将Word转换为文本
        resume_text = docx_to_text(file_content)
        logger.info(f"成功转换简历文本，长度: {len(resume_text)}字符")

        # 生成或使用现有会话ID
        conv_id = conversation_id or str(uuid.uuid4())
        logger.info(f"简历评估请求 - 会话ID: {conv_id}")

        # 模拟评估结果 - 实际应用中替换为您的评估逻辑
        chat_history_backend = get_session_history(conv_id)
        resume_evaluation_chain = get_resume_evaluation_chain()

        enhanced_query = (
            f"用户输入的简历信息为: { resume_text}\n"
        )
        print('enhanced_query:', enhanced_query)

        result =resume_evaluation_chain.invoke({
            "input": enhanced_query,
            "chat_history": chat_history_backend.messages
        })

        # 构建响应 - 实际应用中替换为您的响应生成逻辑
        answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
        print(f"{answer}")
        chat_history_backend.add_user_message(enhanced_query)
        chat_history_backend.add_ai_message(answer)

        return Resume_Evaluate_Response(
            answer=answer,
            conversation_id=conv_id,
            success=True,
        )

    except HTTPException:
        # 重新抛出已处理的HTTP异常
        raise
    except Exception as e:
        logger.exception("简历评估处理失败")
        raise HTTPException(
            status_code=500,
            detail=f"服务器内部错误: {str(e)}"
        )